'use strict';
var rp = require('request-promise');
exports.main = async (event, context) => {
  const {
    name,
    text,token
  } = event
  const res = await uniCloud.httpclient.request(
  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd5144f7cee6bb4f5&secret=faa9c1791b935623e5aa65ad08181d11",
    {
      dataType:"json"
    }
  )
  let ken = res.res.data.access_token
  let url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' + ken;
  let {result} =  await rp({
      url: url,
      method: "POST",
      json: true,
      body: {
        "content": text,
        "version": 2,
        "scene": 2,
        "openid": token
      },
      headers: {
        "content-Type": "application/json",
      },
    })
    if(result.label != 100) {
      return {
    code: 0,
    msg: '含有敏感词，请重新输入'
  }
    }
  if (text.replace(/^\s*|\s*$/g, "")) {
    const db = uniCloud.database()
    const data = await db.collection("leave").add({
      "name": name,
      "text": text
    })
    return {
      code: 1,
      data
    }
  } else return {
    code: 0,
    msg: '留言失败，请稍后再试'
  }
  //返回数据给客户端

};